<?php
/**
 * Created by PhpStorm.
 * User: zhangrxiang
 * Date: 2016/12/21
 * Time: 9:26
 */

class TestIterator implements Iterator{

	private $data;
	private $position;

	function __construct(array $data) {
		$this->data = $data;
		$this->position = 0;
	}

	/**
	 * Return the current element
	 * @link http://php.net/manual/en/iterator.current.php
	 * @return mixed Can return any type.
	 * @since 5.0.0
	 */
	public function current() {
		return $this->data[$this->position];
	}

	/**
	 * Move forward to next element
	 * @link http://php.net/manual/en/iterator.next.php
	 * @return void Any returned value is ignored.
	 * @since 5.0.0
	 */
	public function next() {
		$this->position++;
	}

	/**
	 * Return the key of the current element
	 * @link http://php.net/manual/en/iterator.key.php
	 * @return mixed scalar on success, or null on failure.
	 * @since 5.0.0
	 */
	public function key() {
		return $this->position;
	}

	/**
	 * Checks if current position is valid
	 * @link http://php.net/manual/en/iterator.valid.php
	 * @return boolean The return value will be casted to boolean and then evaluated.
	 * Returns true on success or false on failure.
	 * @since 5.0.0
	 */
	public function valid() {
		return isset($this->data[$this->position]);
	}

	/**
	 * Rewind the Iterator to the first element
	 * @link http://php.net/manual/en/iterator.rewind.php
	 * @return void Any returned value is ignored.
	 * @since 5.0.0
	 */
	public function rewind() {
		$this->position = 0;
	}
}

$it = new TestIterator([1,2,3,4,5,6,7,8,9]);
echo $it->current().PHP_EOL;
$it->next();
echo $it->current().PHP_EOL;
echo $it->key().PHP_EOL;
if($it->valid()){
	echo "valid".PHP_EOL;
}
$it->rewind();
echo $it->current().PHP_EOL;

while ($it->valid()){
	echo $it->current().PHP_EOL;
	$it->next();
}
echo "=========================".PHP_EOL;
foreach ( $it as $item ) {
	echo $item.PHP_EOL;
}


class myIterator implements Iterator {
	private $position = 0;
	private $array = array(
		"firstelement",
		"secondelement",
		"lastelement",
	);

	public function __construct() {
		$this->position = 0;
	}

	function rewind() {
		var_dump(__METHOD__);
		$this->position = 0;
	}

	function current() {
		var_dump(__METHOD__);
		return $this->array[$this->position];
	}

	function key() {
		var_dump(__METHOD__);
		return $this->position;
	}

	function next() {
		var_dump(__METHOD__);
		++$this->position;
	}

	function valid() {
		var_dump(__METHOD__);
		return isset($this->array[$this->position]);
	}
}

$it = new myIterator;

//foreach($it as $key => $value) {
//	var_dump($key, $value);
//	echo "\n";
//}